<template>
  <div>
    <BasicTable
      @register="registerTable"
      :loading="true"
      title="API管理"
      :indentSize="30"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddAPIButtonClick">新增</a-button>
        <a-button type="primary" @click="onimportApiButtonClick"> 导入 </a-button>
      </template>
      <template #method="{ column, record }"> {{ returnMethodType(record) }}</template>
      <template #enableFlag="{ column, record }">
        <template v-if="record.enable && !record.children">
          <Tag :color="'green'">启用</Tag>
        </template>
        <template v-else-if="!record.enable && !record.children">
          <Tag :color="'red'">禁用</Tag>
        </template>
      </template>
      <template #action="{ column, record }">
        <TableAction
          v-if="!record.children"
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditAPIButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteAPIButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateApi @register="registerAddOrUpdateAPIModal" @success="afterSuccess" />
    <ImportApiModal @register="registerImportApi" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onBeforeMount, ref } from 'vue';
  import { apiTableColumns, apiConditionFormSchema } from './api.data';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import ImportApiModal from './ImportApiModal.vue';
  import { Tag } from 'ant-design-vue';
  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import AddOrUpdateApi from './AddOrUpdateApi.vue';
  import { queryAllApi, deleteApi, queryApiTree } from '/@/api/platform/api';
  import { queryEnumOptions } from '/@/api/platform/enum';
  export default defineComponent({
    name: 'apiIndex',
    components: { BasicTable, TableAction, AddOrUpdateApi, ImportApiModal, Tag },
    setup(_, {}) {
      // 请求方法的配置项
      const requestMethodOption = ref([]);
      const [registerAddOrUpdateAPIModal, { openModal: openAddOrUpdateApi }] = useModal();
      const [registerImportApi, { openModal: openImportApi }] = useModal();
      const [registerTable, { reload, getForm }] = useTable({
        api: queryApiTree, //api中指定的为table加载数据对应的查询方法
        columns: apiTableColumns,
        canResize: true,
        striped: false,
        showTableSetting: true,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        indexColumnProps: {
          width: 50,
        },
        afterFetch: (data) => {
          console.log(data, 'treeData');
          let tmp = data.map((item) => {
            return {
              ...item.info,
              apigroup: item.info.apigroup + '(' + item.childs.length + ')',
              children: item.childs,
            };
          });
          return tmp;
        },
        formConfig: {
          labelWidth: 80, //设置查询表单中label的宽度
          schemas: apiConditionFormSchema,
          showResetButton: true, //查询条件部分中是否显示重置按钮
        },
        useSearchForm: true,
        showTableSetting: true,
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      /**
       * 打开新增窗口,将左侧选中的部门id传过去，默认所属部门为左侧选中部门
       */

      function onAddAPIButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: 'API管理',
          operateType: OperationTypeEnum.ADD,
        };
        openAddOrUpdateApi(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditAPIButtonClick(record: APIDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: 'API管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
        };
        openAddOrUpdateApi(true, propsData);
      }

      /**
       * 删除
       * @param record
       */
      function onDeleteAPIButtonClick(record: APIDto) {
        deleteApi(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      /**
       * 导入json文件的openapi，解析
       */
      function onimportApiButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: 'API管理',
          operateType: OperationTypeEnum.CUSTOME,
          operateString: 'Api文件导入',
        };
        openImportApi(true, propsData);
      }
      function returnMethodType(record) {
        for (let i of requestMethodOption.value) {
          if (record.method === i.value) {
            return i.label;
          }
        }
      }
      onBeforeMount(() => {
        queryEnumOptions('RequestMethodEnum')
          .then((res) => {
            // console.log('option res', res);
            if (res != undefined && res != null && res.length > 0x0) {
              let requestOption = res[0].options.map((option) => {
                return {
                  value: Number(option.key),
                  label: option.value,
                };
              });
              requestMethodOption.value = requestOption;
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      });
      return {
        requestMethodOption,
        registerTable,
        registerAddOrUpdateAPIModal,
        afterSuccess,
        onimportApiButtonClick,
        registerImportApi,
        onAddAPIButtonClick,
        onEditAPIButtonClick,
        onDeleteAPIButtonClick,
        returnMethodType,
      };
    },
  });
</script>
